package com.example.sqltest.service.mybatisPlus;

import com.example.sqltest.entity.OrderItem;
import com.example.sqltest.entity.User;
import com.example.sqltest.mapper.OrderItemMapper;
import com.example.sqltest.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.Objects;

@Service
public class UserService {

    @Resource
    UserMapper userMapper;
    @Autowired
    PlatformTransactionManager transactionManager;
    @Autowired
    JdbcTemplate jdbcTemplate;

    public void insert(User user) {
//        TransactionDefinition definition = new DefaultTransactionDefinition();
//        TransactionStatus status = transactionManager.getTransaction(definition);
        Connection connection = DataSourceUtils.getConnection(Objects.requireNonNull(jdbcTemplate.getDataSource()));
        Savepoint savepoint = null;

        try {
            connection.setAutoCommit(false);
            // 设置保存点
            savepoint = connection.setSavepoint();
            userMapper.insert(user);
            connection.commit();
            int i = 1/0;
        } catch (Exception e) {
            if (savepoint != null) {
                try {
                    // 回滚到指定保存点
                    connection.rollback(savepoint);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            } else {
                try {
                    connection.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            if (savepoint != null) {
                try {
                    // 释放保存点
                    connection.releaseSavepoint(savepoint);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            DataSourceUtils.releaseConnection(connection, jdbcTemplate.getDataSource());
        }
    }
}
